<template>
  <view class="container" :style="{ backgroundColor: theme?.background || '#f8f8f8', color: theme?.text || '#333' }">
    <view class="metronome-display">
      <view class="tempo-display">
        <text class="tempo-value" :style="{ color: theme?.primary || '#007AFF' }">{{ tempo }}</text>
        <text class="tempo-unit">BPM</text>
      </view>
      
      <view class="tempo-slider">
        <slider 
          :value="tempo" 
          :min="30" 
          :max="240" 
          :step="1" 
          show-value 
          @change="changeTempo" 
          :activeColor="theme?.primary || '#007AFF'"
        />
        
        <!-- 滑动条刻度标记 -->
        <view class="tempo-marks">
          <view v-for="(mark, index) in tempoMarks" :key="index" class="tempo-mark">
            <view class="mark-line"></view>
            <text class="mark-value">{{ mark }}</text>
          </view>
        </view>
      </view>
      
      <!-- 大号节拍动画指示器 -->
      <view class="beat-animation-container" v-if="isPlaying">
        <view 
          class="beat-animation" 
          :class="{'beat-active': beatAnimation}"
          :style="{
            backgroundColor: beatAnimation 
              ? `rgba(${getRGBA(theme?.primary || '#007AFF', 0.5)})` 
              : `rgba(${getRGBA(theme?.primary || '#007AFF', 0.2)})`,
            borderColor: beatAnimation 
              ? `rgba(${getRGBA(theme?.primary || '#007AFF', 0.8)})` 
              : `rgba(${getRGBA(theme?.primary || '#007AFF', 0.4)})`,
            boxShadow: beatAnimation 
              ? `0 0 30rpx rgba(${getRGBA(theme?.primary || '#007AFF', 0.7)})` 
              : 'none',
            background: beatAnimation 
              ? `linear-gradient(135deg, rgba(${getRGBA(theme?.primary || '#007AFF', 0.6)}) 0%, rgba(${getRGBA(theme?.primary || '#007AFF', 0.4)}) 100%)` 
              : `linear-gradient(135deg, rgba(${getRGBA(theme?.primary || '#007AFF', 0.25)}) 0%, rgba(${getRGBA(theme?.primary || '#007AFF', 0.15)}) 100%)`
          }"
        >
          <text 
            class="beat-animation-text"
            :style="{ 
              color: beatAnimation ? '#FFFFFF' : theme?.primary || '#007AFF',
              textShadow: beatAnimation ? '0 2px 8px rgba(0,0,0,0.3)' : '0 2px 4px rgba(0,0,0,0.1)'
            }"
          >{{ currentBeat >= 0 ? currentBeat + 1 : '' }}</text>
        </view>
      </view>
      
      <!-- 当前拍数提示 -->
      <view class="current-beat-display" v-if="isPlaying">
        <text class="current-beat-label">当前拍:</text>
        <text class="current-beat-value" :style="{ color: theme?.primary || '#007AFF' }">
          {{ currentBeat >= 0 ? currentBeat + 1 : '-' }}
        </text>
        <text class="current-beat-total">/ {{ getBeatCount() }}</text>
      </view>
      
      <view class="beat-selector">
        <text>拍号:</text>
        <picker @change="changeTimeSignature" :value="timeSignatureIndex" :range="timeSignatures">
          <view class="time-signature-picker" :style="{ backgroundColor: theme?.background || '#f5f5f5' }">
            {{ timeSignatures[timeSignatureIndex] }}
          </view>
        </picker>
      </view>
      
      <!-- 使用自定义BeatVisualizer组件 -->
      <beat-visualizer 
        :timeSignature="timeSignatures[timeSignatureIndex]"
        :currentBeat="currentBeat"
        :accentColor="theme?.primary || '#007AFF'"
      ></beat-visualizer>
    </view>
    
    <view class="controls">
      <button 
        class="control-btn" 
        @tap="togglePlay"
        :style="{ backgroundColor: theme?.primary || '#007AFF', color: theme?.text === '#FFFFFF' ? theme.text : 'white' }"
      >
        {{ isPlaying ? '停止' : '开始' }}
      </button>
      <button 
        class="tap-tempo-btn" 
        @tap="tapTempo"
        :style="{ backgroundColor: theme?.background || '#f0f0f0', color: theme?.text || '#333' }"
      >
        点击计算速度
      </button>
      
      <!-- 测试木鱼声按钮 -->
      <button 
        class="test-sound-btn" 
        @tap="testWoodblockSound"
        :style="{ backgroundColor: theme?.secondary || '#4CAF50', color: 'white' }"
      >
        测试木鱼声
      </button>
      
      <!-- 成功提示 -->
      <view class="sound-fixed-tip" v-if="showFixedTip">
        <text>木鱼声已修复！</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import metronomeService from '../../utils/metronomeService.js';
import themeService from '../../utils/themeService.js';
import BeatVisualizer from '../../components/BeatVisualizer.vue';

// 数据状态
const tempo = ref(60); // 默认速度为60
const isPlaying = ref(false);
const timeSignatures = ref(['4/4', '3/4', '2/4', '6/8', '5/4']);
const timeSignatureIndex = ref(0);
const currentBeat = ref(-1);
const tapTimes = ref([]);
const lastTapTime = ref(0);
const metronome = ref(null);
const theme = ref(null);

// 速度刻度
const tempoMarks = computed(() => {
  const marks = [];
  for (let i = 30; i <= 240; i += 30) {
    marks.push(i);
  }
  return marks;
});

// 节拍动画控制
const beatAnimation = ref(false);

// 计算属性
const beatsArray = computed(() => {
  const timeSig = timeSignatures.value[timeSignatureIndex.value];
  const beats = parseInt(timeSig.split('/')[0]);
  return new Array(beats).fill(0);
});

// 方法
function loadSettings() {
  try {
    const settings = uni.getStorageSync('metronomeSettings');
    if (settings) {
      // 应用保存的设置
      tempo.value = settings.defaultTempo || 60; // 默认值为60
      timeSignatureIndex.value = settings.defaultTimeSignatureIndex || 0;
      
      // 如果有声音和振动设置，应用到节拍器
      if (typeof settings.soundTypeIndex !== 'undefined') {
        // 使用metronomeService而不是metronome.value
        metronomeService.setSoundType(settings.soundTypeIndex);
        metronomeService.setVolume(settings.volume / 100 || 0.8);
        metronomeService.setVibration(
          typeof settings.vibrationEnabled !== 'undefined' ? settings.vibrationEnabled : true
        );
      } else {
        // 确保使用默认的木鱼声
        metronomeService.setSoundType(1);
      }
    } else {
      // 如果没有保存的设置，确保使用默认值
      tempo.value = 60;
      metronomeService.setTempo(60);
      metronomeService.setSoundType(1); // 默认使用木鱼声
    }
  } catch (e) {
    console.error('加载设置失败:', e);
    // 出错时也设置默认值
    tempo.value = 60;
    metronomeService.setTempo(60);
    metronomeService.setSoundType(1);
  }
}

function onBeatUpdate(beatIndex) {
  currentBeat.value = beatIndex;
  isPlaying.value = metronomeService.isPlaying;
}

function changeTempo(e) {
  tempo.value = e.detail.value;
  metronomeService.setTempo(tempo.value);
}

function changeTimeSignature(e) {
  timeSignatureIndex.value = e.detail.value;
  currentBeat.value = -1;
  
  const timeSigStr = timeSignatures.value[timeSignatureIndex.value];
  const beats = parseInt(timeSigStr.split('/')[0]);
  metronomeService.setTimeSignature(beats);
}

function togglePlay() {
  if (metronomeService.isPlaying) {
    metronomeService.stop();
  } else {
    metronomeService.start();
  }
  isPlaying.value = metronomeService.isPlaying;
}

function tapTempo() {
  const now = Date.now();
  
  // 如果是第一次点击或超过2秒重置
  if (lastTapTime.value === 0 || now - lastTapTime.value > 2000) {
    tapTimes.value = [now];
    lastTapTime.value = now;
    return;
  }
  
  tapTimes.value.push(now);
  lastTapTime.value = now;
  
  // 保留最近的8次点击
  if (tapTimes.value.length > 8) {
    tapTimes.value.shift();
  }
  
  // 至少有2次点击才计算
  if (tapTimes.value.length >= 2) {
    let sum = 0;
    for (let i = 1; i < tapTimes.value.length; i++) {
      sum += tapTimes.value[i] - tapTimes.value[i - 1];
    }
    
    const avgInterval = sum / (tapTimes.value.length - 1);
    const newTempo = Math.round(60000 / avgInterval);
    
    // 确保速度在合理范围内
    tempo.value = Math.max(30, Math.min(240, newTempo));
    
    metronomeService.setTempo(tempo.value);
  }
}

// 测试木鱼声播放
function testWoodblockSound() {
  // 设置木鱼声(索引1)并测试播放
  console.log('测试木鱼声播放');
  
  // 强拍
  metronomeService.testAudio(1, true);
  
  // 延迟0.5秒后播放弱拍
  setTimeout(() => {
    metronomeService.testAudio(1, false);
  }, 500);
}

// 获取当前拍号的总拍数
function getBeatCount() {
  const timeSig = timeSignatures.value[timeSignatureIndex.value];
  return parseInt(timeSig.split('/')[0]);
}

// 监听currentBeat的变化，触发动画
watch(currentBeat, (newValue, oldValue) => {
  if (newValue >= 0 && isPlaying.value) {
    // 激活动画
    beatAnimation.value = true;
    
    // 200ms后重置动画
    setTimeout(() => {
      beatAnimation.value = false;
    }, 200);
  }
});

// 生命周期钩子
onLoad(() => {
  // 加载设置
  loadSettings();
  
  // 初始化主题
  theme.value = themeService.getCurrentTheme();
  
  // 检查音频是否正常工作
  checkAudioWorks();
  
  // 初始化节拍器
  initMetronome();
});

// 检查音频是否正常工作
function checkAudioWorks() {
  // 测试本地文件是否可用
  metronomeService.testLocalFiles().then(available => {
    if (!available) {
      console.log('本地音频文件测试失败');
      
      uni.showToast({
        title: '音频文件加载失败',
        icon: 'none',
        duration: 2000
      });
    } else {
      console.log('本地音频文件测试通过');
    }
  });
}

// 初始化节拍器
function initMetronome() {
  // 应用设置
  metronomeService.setTempo(tempo.value);
  
  // 设置拍号
  const timeSigStr = timeSignatures.value[timeSignatureIndex.value];
  const beats = parseInt(timeSigStr.split('/')[0]);
  metronomeService.setTimeSignature(beats);
  
  // 设置回调
  metronomeService.setOnBeatCallback((beatIndex, isAccent) => {
    currentBeat.value = beatIndex - 1; // 转换为0-based索引以配组件
    isPlaying.value = metronomeService.isPlaying;
    
    // 每次节拍时激活动画
    beatAnimation.value = true;
    setTimeout(() => {
      beatAnimation.value = false;
    }, 200);
  });
}

onUnmounted(() => {
  // 停止节拍器
  if (metronomeService.isPlaying) {
    metronomeService.stop();
  }
});

// 将HEX颜色转换为RGBA格式
function getRGBA(hex, alpha) {
  // 去掉可能存在的#前缀
  hex = hex.replace(/^#/, '');
  
  // 解析RGB值
  let r, g, b;
  if (hex.length === 3) {
    r = parseInt(hex[0] + hex[0], 16);
    g = parseInt(hex[1] + hex[1], 16);
    b = parseInt(hex[2] + hex[2], 16);
  } else {
    r = parseInt(hex.substring(0, 2), 16);
    g = parseInt(hex.substring(2, 4), 16);
    b = parseInt(hex.substring(4, 6), 16);
  }
  
  // 返回逗号分隔的RGB值和提供的alpha
  return `${r}, ${g}, ${b}`;
}
</script>

<style>
.container {
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100vh;
  box-sizing: border-box;
}

.metronome-display {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 60rpx;
}

.tempo-display {
  display: flex;
  align-items: baseline;
  margin-bottom: 30rpx;
}

.tempo-value {
  font-size: 120rpx;
  font-weight: bold;
}

.tempo-unit {
  font-size: 40rpx;
  margin-left: 10rpx;
  color: #666;
}

.tempo-slider {
  width: 100%;
  margin: 40rpx 0;
  position: relative;
}

.tempo-marks {
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding: 0 15rpx;
  box-sizing: border-box;
  margin-top: 10rpx;
}

.tempo-mark {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 30rpx;
}

.mark-line {
  height: 12rpx;
  width: 2rpx;
  background-color: #aaa;
  margin-bottom: 6rpx;
}

.mark-value {
  font-size: 20rpx;
  color: #666;
}

.beat-selector {
  display: flex;
  align-items: center;
  margin: 20rpx 0;
}

.time-signature-picker {
  margin-left: 20rpx;
  padding: 10rpx 30rpx;
  border-radius: 10rpx;
}

.controls {
  margin-top: 40rpx;
  display: flex;
  flex-direction: column;
}

.control-btn {
  font-size: 38rpx;
  height: 100rpx;
  line-height: 100rpx;
  margin-bottom: 30rpx;
}

.tap-tempo-btn {
  font-size: 32rpx;
  height: 80rpx;
  line-height: 80rpx;
}

.test-sound-btn {
  margin-top: 10rpx;
  background-color: #4CAF50;
  color: white;
}

.current-beat-display {
  display: flex;
  align-items: baseline;
  margin: 10rpx 0 20rpx;
}

.current-beat-label {
  font-size: 28rpx;
  color: #666;
  margin-right: 10rpx;
}

.current-beat-value {
  font-size: 48rpx;
  font-weight: bold;
}

.current-beat-total {
  font-size: 32rpx;
  color: #666;
  margin-left: 5rpx;
}

.beat-animation-container {
  width: 100%;
  display: flex;
  justify-content: center;
  margin: 20rpx 0 40rpx;
}

.beat-animation {
  width: 320rpx;
  height: 220rpx;
  border-radius: 16rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.2s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  border: 8rpx solid transparent;
  position: relative;
  overflow: hidden;
}

.beat-animation:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(45deg, transparent 0%, rgba(255,255,255,0.3) 100%);
  z-index: 0;
}

.beat-animation.beat-active {
  transform: scale(1.15);
}

.beat-animation-text {
  font-size: 140rpx;
  font-weight: bold;
  position: relative;
  z-index: 1;
  transition: all 0.2s ease;
}
</style> 